package fast;

import java.util.*;

/**
 * Peermanager class
 * 
 * Maintains a map of host to port assignments
 * 
 * 
 * @author Adam Bell
 * @version 0.1
 * @date 08/02/2010
 */
public class PeerManager {

	private Map<String, Integer> peers = new HashMap<String, Integer>();

	/**
	 * Returns the number of hosts with a mapped port number
	 * 
	 * @return The number of hosts
	 */
	public int getCount() {
		return peers.size();
	}

	/**
	 * Returns a 2D array representing the current map
	 * 
	 * @return A 2D array, where the first column is the IP address and the
	 *         second column is the mapped port address
	 */
	public String[][] getAllPeers() {

		String[][] peerArray = new String[peers.size()][2];
		Iterator it = peers.entrySet().iterator();

		int i = 0;
		while (it.hasNext()) {

			String s = it.next().toString();

			peerArray[i][0] = s.substring(0, s.indexOf("="));
			peerArray[i][1] = s.substring(s.indexOf("=") + 1, s.length());
			i++;
		}

		return peerArray;
	}

	/**
	 * Add a host to port mapping to the map
	 * 
	 * @param peer
	 * @param port
	 */
	public void addPeer(String peer, int port) {
		if (!peers.containsKey(peer)) {
			peers.put(peer, port);
		}
	}

	/**
	 * Get the port mapping for a particular host
	 * 
	 * @param peer
	 * @return Port that the host is mapped to
	 */
	public int getPort(String peer) {

		if (peers.containsKey(peer)) {
			return peers.get(peer);
		} else {
			// return default
			return 10001;
		}
	}

	/**
	 * Remove a host to port mapping
	 * 
	 * @param peer
	 */
	public void removePeer(String peer) {
		if (peers.containsKey(peer)) {
			peers.remove(peer);
		}
	}

	/**
	 * Check whether a host has a mapped port
	 * 
	 * @param peer
	 * @return true if a match found, false otherwise
	 */
	public boolean contains(String peer) {
		return peers.containsKey(peer);
	}
}
